package com.cyb.binojbackendjudgeservice.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 初始化RabbitMQ
 */
@Slf4j
@Component
@ConfigurationProperties(prefix = "spring.rabbitmq")
@Data
public class initRabbitMq {

    private String username;

    private String password;

    private String host;

    private int port;

    private String virtualHost;

    @PostConstruct
    public void doInit() {
        try {
            // 创建连接工厂
            ConnectionFactory factory = new ConnectionFactory();
            // 设置 RabbitMQ 的主机名
            factory.setHost(host);
            factory.setUsername(username);
            factory.setPassword(password);
            factory.setVirtualHost(virtualHost);
            factory.setPort(port);
            factory.setConnectionTimeout(30000);
            factory.setHandshakeTimeout(10000);
            //创建一个新的连接
            Connection connection = factory.newConnection();
            // 创建一个通道
            Channel channel = connection.createChannel();
            //声明一个交换机名称
            String EXCHANGE_NAME = "code_exchange";
            //声明一个为direct 类型的交换机
            channel.exchangeDeclare(EXCHANGE_NAME, "direct");

            // 创建队列，随机分配一个队列名称
            String queueName = "code_queue";
            channel.queueDeclare(queueName, true, false, false, null);
            channel.queueBind(queueName, EXCHANGE_NAME, "my_routingKey");
            log.info("RabbitMQ初始化成功");
        } catch (Exception e) {
            log.error("RabbitMQ初始化失败", e);
        }
    }

    public static void main(String[] args) {
        initRabbitMq initRabbitMq = new initRabbitMq();
        initRabbitMq.doInit();
    }
}
